package com.soft.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import com.soft.constant.Constant;
import com.soft.util.DateUtil;

@WebServlet(value = "/HttpsProcess", asyncSupported = false)
public class HttpsProcess extends HttpServlet {
	
	public static final Logger logger = Logger.getLogger("BusinessLog");
	
	 private static String USER = "sunyard";
	  private static String PASSWORD = "admin123";
	  
	private static String SUCCESS = "0000";
	private static String UPLOAD_ERR = "0001";
	private static String LOGON_USER_PASSWORD_ERR = "0002";
	private static String EXCEPTION_ERR = "0003";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		logger.info("控件上传开始请求HttpsProcess");
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(4096);
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setSizeMax(104857600L);
		try {
			List<FileItem> list = upload.parseRequest(req);
			Iterator<FileItem> iter = list.iterator();
			File zipTempfile = null;
			String name = "";
			String[] arrString = null;
			String batchTemPath = Constant.tempPath + File.separator + "sendFolder" + File.separator + DateUtil.getDateStrCompact();
			File tempFile = new File(batchTemPath);
			if (!tempFile.exists()) {
				tempFile.mkdirs();
			}
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (item.isFormField()) {
					String fieldValue = new String(item.getString().getBytes("ISO8859_1"), "utf-8");
					System.out.println("fieldValue=" + fieldValue);
					Hex hex = new Hex();
					byte[] hFieldValue = (byte[]) hex.decode(fieldValue);
					fieldValue = new String(hFieldValue);
					logger.info("控件使用HTTP上传:" + fieldValue);

					Base64 base64 = new Base64();
					byte[] dFieldValue = base64.decode(hFieldValue);
					fieldValue = new String(dFieldValue);

					arrString = fieldValue.split(",");
					String user = "";
					String password = "";
					if (arrString.length > 0) {
						if ((arrString[3] != null) || (arrString[4] != null)) {
							user = arrString[3];
							password = arrString[4];
						} else {
							throw new Exception("filed value is err ,pls check it then try again");
						}
					}
					if ((!user.equalsIgnoreCase(USER))|| (!password.equalsIgnoreCase(PASSWORD))) {
						resp.setHeader("retcode", LOGON_USER_PASSWORD_ERR);
					}

				} else {
					name = item.getName();
					logger.info("文件名称item.getName=" + name);
					zipTempfile = new File(batchTemPath + File.separator + name);
					logger.info("文件路径=" + zipTempfile.getAbsolutePath());
					item.write(zipTempfile);
				}
			}
			if(zipTempfile==null){
				logger.info("控件上传的文件不存在");
				resp.setHeader("retcode", UPLOAD_ERR);
				return ;
			}
			 File batchTemFile = new File(batchTemPath + File.separator + UUID.randomUUID().toString());
		      if (!batchTemFile.exists()) {
		        batchTemFile.mkdirs();
		      }
		      boolean flag = false;
		      try {
		    	  flag = unZipFile(zipTempfile,batchTemFile);
				} catch (Exception e) {
					logger.error("解压文件出现异常", e);
				}
		      //FileProcess.deleteFolder(zipTempfile);
		      if (flag) {
					int count = batchTemFile.list().length;
					logger.info("解压后文件count="+count);
					
					
					if(count==1){
						resp.setHeader("retcode", new String("解压后文件数量为1个".getBytes(),"ISO8859-1"));
					}else{
						resp.setHeader("retcode", SUCCESS);
					}
				}else{
					
					resp.setHeader("retcode", UPLOAD_ERR);
					//writeStr(resp, "解压出错了");
				}
		} catch (Exception e) {
			e.printStackTrace();
			resp.setHeader("retcode", EXCEPTION_ERR);
		}
		
		
	}
	
	
	
	
	// 解压zip 生产文件夹
    public static boolean unZipFile(File zipTempfile,File batchTemFile) throws ZipException {  
    
        ZipFile zFile = new ZipFile(zipTempfile);  // 首先创建ZipFile指向磁盘上的.zip文件  
        zFile.setFileNameCharset("GBK");       // 设置文件名编码，在GBK系统中需要设置  
        if (!zFile.isValidZipFile()) {   // 验证.zip文件是否合法，包括文件是否存在、是否为zip文件、是否被损坏等  
            throw new ZipException("压缩文件不合法,可能被损坏.");  
        }    
        zFile.extractAll(batchTemFile.getAbsolutePath());      // 将文件抽出到解压目录(解压)  
        return true;
    }  
    
    
    /**
	 * 向页面输出
	 * 
	 * @param response
	 * @param obj
	 */
	public static void writeStr(HttpServletResponse response, Object obj) {
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
			writer.print(obj);
			writer.flush();
		} catch (IOException e) {
		
		} finally {
			if (writer != null) {
				writer.close();
			}
		}
	}
}
